package org.example.rowing.controller;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.FormatterUtil;
import org.example.rowing.domain.Athlete;
import org.example.rowing.domain.Team;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.enums.GenderEnum;
import org.example.rowing.service.TeamInfoService;
import org.example.rowing.vo.AthleteVO;
import org.example.rowing.vo.EventVO;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.TeamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class UpdateAthleteController {
    @FXML
    public ComboBox<String> genderField;
    @FXML
    public ComboBox<String> categoryField;
    @FXML
    private TextField athleteNameField;
    @FXML
    public ComboBox<Team> teamNameField;
    @FXML
    private DatePicker dateField;
    @FXML
    private Label popupTitle;
    private AthleteVO athleteToEdit;

    @Autowired
    private TeamInfoService teamInfoService;


    // 用于在弹出框初始化时设置事件信息（用于编辑）
    public void initialize(AthleteVO athlete) {
        // 设置转换器，使下拉框只显示 eventName
        teamNameField.setConverter(new StringConverter<Team>() {
            @Override
            public String toString(Team team) {
                return team == null ? "" : team.getId() + ". " + team.getName();
            }
            @Override
            public Team fromString(String string) {
                // 一般不需要转换回对象，可返回 null 或自行实现
                return null;
            }
        });

        if (athlete != null) {
            this.athleteToEdit = athlete;
            popupTitle.setText("修改个人信息");
            athleteNameField.setText(athlete.getName());
            dateField.setValue(LocalDate.parse(athlete.getBirthDate()));

            // 根据给定的内容设置 raceTypeField 的默认选项
            genderField.setItems(FXCollections.observableArrayList("男子","女子"));
            genderField.setValue(athlete.getGenderEnum().getDisplayName());
            categoryField.setItems(FXCollections.observableArrayList("","甲组","乙组","丙组"));
            categoryField.setValue(athlete.getCategory());
            loadTeams();
            teamNameField.setValue(athlete.getTeam());
        } else {
            popupTitle.setText("添加个人信息");
            genderField.setItems(FXCollections.observableArrayList("男子","女子"));
            categoryField.setItems(FXCollections.observableArrayList("","甲组","乙组","丙组"));
            loadTeams();
            this.athleteToEdit = null;
        }
    }

    private void loadTeams() {
        List<TeamVO> teamVOS = teamInfoService.showTeamsByBoatType(BoatTypeEnum.ROWING);
        List<Team> teams = new ArrayList<>();
        for (TeamVO teamVO : teamVOS) {
            Team team = new Team(teamVO.getId(), teamVO.getEventVO().getId(), teamVO.getName(), teamVO.getCountry(), teamVO.getCoachName(), teamVO.getInfo(), null);
            teams.add(team);
        }
        teamNameField.setItems(FXCollections.observableArrayList(teams));
    }

    // 保存赛事
    @FXML
    private void handleSaveEvent() {
        String athleteName = athleteNameField.getText();
        LocalDate birthDate = dateField.getValue();
        String gender = genderField.getValue();
        String category = categoryField.getValue();
        Team team = teamNameField.getValue();

        if (team == null || gender == null || birthDate == null || athleteName.isEmpty()) {
            log.warn("请填写完整的信息");
            showErrorDialog("请填写完整的信息");
            return;
        }

        if (team.getId() == null) {
            log.error("队伍信息未找到，无法保存该信息");
            showErrorDialog("队伍信息未找到");
            return;
        }

        Athlete athlete = new Athlete(null, team.getId(), athleteName, birthDate.toString(), GenderEnum.fromDisplayName(gender), category);

        if (athleteToEdit == null) {
            // 添加赛事
            log.info("添加新成员: {}", athlete);
        } else {
            // 修改赛事
            athlete.setId(athleteToEdit.getId());  // 保持修改的赛事ID
            log.info("修改选手: {}", athlete);
        }
        teamInfoService.saveOrUpdateAthlete(athlete);

        // 关闭弹窗
        closeWindow();
    }

    // 取消操作，关闭弹出框
    @FXML
    private void handleCancel() {
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) teamNameField.getScene().getWindow();
        stage.close();
    }

    // 弹出错误提示框
    private void showErrorDialog(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("输入错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
